import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TimeConfigClass } from '../../../common/common-config';
import { StorageService } from "app/common/storage.service";
import { SelfdynamicService } from './selfdynamic.service';

@Component({
  selector: 'app-selfdynamic',
  templateUrl: './selfdynamic.component.html',
  styleUrls: ['./selfdynamic.component.css'],
  providers: [SelfdynamicService]
})
export class SelfdynamicComponent implements OnInit {
  //列表
  timeConfig: any = new TimeConfigClass(); // 时间空间初始化
  loading: boolean = true;
  colsSelected: any;
  cols: any = [];
  selectedItem: any = []; //选中记录
  pageSize: number; // 每页条数
  pageNo: number; // 当前页
  listData: any = []; // 数据
  totalRecords: number; // 数据条数
  searchObj: any = {}; // 搜索条件
  searcSortObj: any = {}; // 排序信息


  //表单
  isShow: boolean = false; //弹窗a
  isEdit: boolean = false;
  isAdd: boolean = false;
  showTitle: string = '';
  dateKey: string = '';//数据标识
  baseObj: any = {};//原始数据
  formObj: any = {};//表单数据
  formOptObj: any = {};//表单选中数据
  imageArr = [];  //标题照片
  errorObj: any = {};//错误信息

  sendTypeArr: any = [];  //发送对象 表单
  sendTypeArr_s: any = [];  //发送对象 列表
  sendstatusArr: any = [];  //发送状态
  lookImagesUrl: string = '';

  uploadRrl: String = 'zuul/com-dyrs-mtsp-fileservice/fileservice/fileDFSSave/api'; // 上传图片地址

  constructor(private storage: StorageService, private router: Router, private server: SelfdynamicService) {
    this.cols = [
      { field: 'code', header: '编号', frozen: false, sortable: true, tem: true, width: '15%' },
      { field: 'title', header: '标题', sortable: true, width: '15%' },
      { field: 'imagePath', header: '封面图', tem: true, width: '10%' },
      { field: 'forwardUrl', header: '跳转链接', tem: true, frozen: false, sortable: true, width: '18%' },
      { field: 'sendTypeDic', header: '发送对象', sortable: true, width: '10%' },
      { field: 'sendTimeDic', header: '发送时间', sortable: true, width: '10%' },
      { field: 'sendstatusDic', header: '状态', sortable: true, width: '10%' }
    ];
    this.colsSelected = this.cols;
  }

  ngOnInit() {
    this.uploadRrl = (this.server.httpService.baseUrl || 'http://172.18.8.76/') + this.uploadRrl;
    this.getDictionaries();
  }

  //打开新窗口
  openWin(url) {
    window.open(url, 'target', '');
  }

  //撤回
  withdraw() {
    let list = this.selectedItem;
    if (list.length < 1) {
      this.warning2();
      return false;
    }
    let ids = [];
    for (let index in list) {
      ids.push(list[index].code)
    }
    this.storage.makesureService.emit({
      message: '确定要撤回您选定的' + list.length + '项吗?',
      header: '提示',
      icon: 'fa fa-question-circle',
      accept: () => {
        this.loading = true;
        this.server.withdraw(ids.join(",")).then(
          data => {
            this.loading = false;
            if (data.result) {
              const params = Object.assign(this.searchObj, this.searcSortObj);
              this.getData(params);
              this.success();
              this.selectedItem = [];
              console.log('操作成功!');
            } else {
              this.error();
              console.log('后台错误！');
            }
          }
        );
      },
      reject: () => { }
    });

  }

  //删除
  delete() {
    let list = this.selectedItem;
    if (list.length < 1) {
      this.warning2();
      return false;
    }
    let ids = [];
    for (let index in list) {
      ids.push(list[index].code)
    }
    this.storage.makesureService.emit({
      message: '确定要删除您选定的' + list.length + '项吗?',
      header: '提示',
      icon: 'fa fa-question-circle',
      accept: () => {
        this.loading = true;
        this.server.delete(ids.join(",")).then(
          data => {
            this.loading = false;
            if (data.result) {
              const params = Object.assign(this.searchObj, this.searcSortObj);
              this.getData(params);
              this.success();
              this.selectedItem = [];
              console.log('操作成功!');
            } else {
              this.error();
              console.log('后台错误！');
            }
          }
        );
      },
      reject: () => { }
    });

  }

  /**
   * 获取数据
   */
  getData(params) {
    //let params = this.searchObj;
    this.loading = true;
    this.server.list(params, this.pageSize, this.pageNo).then(
      data => {
        this.loading = false;
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
        } else {
          this.listData = [];
          this.totalRecords = 0;
          console.log('后台错误！');
        }
      }
    );
  }
  /**
   * 改变模糊搜索框数据值
   */
  searchTextChange(event) {
    if (event == undefined)
      return false
    if (event.constructor == String && event != '') {
      this.searchObj['searchValue'] = event;
    } else {
      this.searchObj['searchValue'] = undefined;
    };
  }
  /**
   * 搜索方法
   * @param event
   */
  search(event?) {
    //筛选查询
    this.searchTextChange(event);
    // this.pageNo = 1;
    const params = Object.assign(this.searchObj);
    this.getData(params);
  }
  /**
   * 分页查询
   * @param event
   */
  loadCarsLazy(event) {
    this.pageSize = + event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    this.searcSortObj['sortF'] = event.sortField;
    this.searcSortObj['sortO'] = event.sortOrder == 1 ? 'asc' : 'desc';
    const params = Object.assign(this.searchObj, this.searcSortObj);
    this.getData(params);
  }

  /**
  * 加载字典项
  */
  getDictionaries() {
    // 加载工种和工人状态
    this.server.getDictionaries().then(
      data => {
        if (data.result) {
          //发送对象
          this.sendTypeArr = data.data.source;
          //发送对象  列表
          this.sendTypeArr_s = (data.data.source).slice(0);
          this.sendTypeArr_s.unshift({ code: '', name: '全部' });
          //发送状态
          this.sendstatusArr = data.data.sendstatus;
          this.sendstatusArr.unshift({ code: '', name: '全部' });
        } else {
        };
      }
    );
  }

  /*****表单 */
  /**
   * 重置表单数据
   */
  resetFormDate() {
    this.isShow = false; //弹窗a
    this.isEdit = false;
    this.isAdd = false;
    this.dateKey = '';
    this.baseObj = {};//原始数据
    this.formObj = {};
    this.formOptObj = {};
    this.imageArr = [];  //标题照片
    this.errorObj = {};//错误信息
  }

  /**
   * 添加
   */
  add() {
    this.resetFormDate();
    this.isShow = true;
    this.isEdit = true;
    this.isAdd = true;
    this.showTitle = '新建动态';
  }

  /**
   * 编辑
   */
  edit(code) {
    if (code == undefined) {
      this.error();
      return false;
    }
    this.resetFormDate();
    this.dateKey = code;
    this.getFormData(this.dateKey);
  }

  /**
   * 获取数据
   */
  getFormData(code) {
    this.loading = true;
    this.server.get(code).then(data => {
      this.loading = false;
      if (data.result) {
        this.showTitle = '动态修改';
        this.formObj = data.data;
        this.baseObj = Object.assign({}, data.data);
        this.formOptObj.sendType = this.formObj.sendType.split(',')
        this.imgUrlData(this.formObj.imagePath, 'imageArr');
        this.isShow = true;
        console.log('查询成功')
      } else {
        this.error();
        console.log('查询失败')
      }
    });
  }

  /**
   * 保存
   */
  save() {
    //自定义验证
    if (!this.verifyCustom()) {
      return false;
    }
    let params = this.formObj
    if (this.formOptObj.sendType) {
      params['sendType'] = this.formOptObj.sendType.filter(item => item != '').toString();
    }
    console.log(params)
    this.loading = true;
    this.server.save(params).then(data => {
      this.loading = false;
      if (data.result) {
        const params = Object.assign(this.searchObj, this.searcSortObj);
        // this.getData(params);
        if (this.dateKey == '') {
          this.isShow = false;
        } else {
          this.isEdit = false;
          this.showTitle = '动态查看';
          this.getFormData(this.dateKey);
        }
        // console.log('保存成功')
      } else {
        this.error();
        console.log('保存失败')
      }
    });
  }

  /**
   * 发送对象 验证
   */
  changeSendType() {
    let arr = (this.formOptObj.sendType == undefined) ? [] : this.formOptObj.sendType;
    if (arr.length < 1) {
      this.errorObj['sendType'] = { show: true };
      return true;
    }
    if (this.errorObj['sendType']) {
      delete this.errorObj['sendType'];
    }
    return false;
  }
  /**
   * 发送时间 验证
   */
  changeSendTime() {
    if (this.formObj['sendTime_date'] == undefined || this.formObj['sendTime_time'] == undefined) {
      this.errorObj['sendTime'] = { show: true };
      return true;
    };
    const sendTime = this.formObj.sendTime_date + ' ' + this.formObj.sendTime_time + ':00';
    if (this.baseObj.sendTime != sendTime && new Date(sendTime) < new Date()) {
      this.errorObj['sendTime'] = { low: true };
      return true;
    };
    // this.server.getSystemTime().then(data => {
    //     if (data.result&&data.data>t) {
    //         this.errorObj['sendTime'] = {show:true};
    //         return true;
    //       }else{
    //         return false;
    //     };
    //   }
    // );
    if (this.errorObj['sendTime']) {
      delete this.errorObj['sendTime'];
    };
    return false;
  }
  /**
   * 封面图 验证
   */
  changeImges() {
    if (this.imageArr.length < 1) {
      this.errorObj['image'] = { show: true };
      return true;
    }
    if (this.errorObj['image']) {
      delete this.errorObj['image'];
    }
    return false;
  }

  /**
   * 自定义验证
   */
  verifyCustom() {
    const a = this.changeSendType();
    const b = this.changeSendTime();
    const c = this.changeImges();
    if (a || b || c) {
      this.errorObj['e'] = true;
      return false;
    }
    if (this.errorObj['e']) {
      delete this.errorObj['e'];
    }
    return true;
  }

  /**
   * 验证字段信息显示
   */
  verifyFields(e, obj) {
    if (e == undefined || e['name'] == undefined || obj == undefined) {
      return false;
    };
    let err = { show: true };
    if (e['value'] == undefined || e.value.trim() == '') {
      err['blank'] = true;
    };
    this.errorObj[e.name] = err;
    obj[e.name] = e['value'] == undefined ? '' : e.value.trim();
    // console.log('verifyFields')
  }
  /**
   * 清除验证信息提示框
   */
  clearVerify(e) {
    if (e == undefined) {
      return false;
    }
    //this.errorObj[e.name] = { show: false };
    this.errorObj[e.name] = undefined;
    //console.log('clearVerify')
  }

  /**
   * 改变时间
   */
  calendarChange(e) {
    console.log('44!');
  }

  /**
  * 上传单张图片验证
  */
  onSelect(event, obj) {
    if (obj.onlyImg == 'true' && event.files.length > 1) {
      this.warning2("只能选择一张图片！");
      obj.clear();
      return false;
    }
    event.upload();
  }

  /**
  * 图片上传回调函数
  * @param event
  * @param f
  */
  onUpload(event, f) {
    const result = JSON.parse(event.xhr.responseText);
    console.log('上传图片', result);
    if (result && result.result && result.data) {
      this.formObj[f.cancelLabel] = (this.formObj[f.cancelLabel] && f.onlyImg != 'true') ? this.formObj[f.cancelLabel] + ',' + result.data.fileCode : result.data.fileCode;
      this.imgUrlData(result.data.filePath, f.cancelLabel + 'Arr', f.onlyImg);
    };
  }
  /**
   * 展示图片数据
   */
  imgUrlData(fileUrl: string, fileArr: any, isClear?: string) {
    if (!fileUrl || !fileArr) {
      return false;
    };
    if (isClear == undefined || isClear == 'true') {
      this[fileArr] = [];
    };
    for (let item of fileUrl.split(',')) {
      this[fileArr] = [...this[fileArr], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    };
  }
  /**
  *删除图片并更新对应的图片数据
  * @param event
  * @param f
  */
  removeItem(event, f) {
    //console.log(f);
    let codeArray = this.formObj[f].split(',');
    codeArray.splice(event.index, 1);
    this.formObj[f] = codeArray.join(',');
    this[f + 'Arr'] = this[f + 'Arr'].filter((val, index) => index !== event.index);
  }



  /**
   * 提示框
   */
  success(msg?: string) {
    msg = msg != undefined ? msg : '操作成功';
    this.storage.messageService.emit({ severity: 'success', detail: msg });
  }
  error(msg?: string) {
    msg = msg != undefined ? msg : '请选择要操作的数据！';
    this.storage.messageService.emit({ severity: 'error', detail: msg });
  }
  warning(msg?: string) {
    msg = msg != undefined ? msg : '请选择要操作的数据！';
    this.storage.messageService.emit({ severity: 'warn', detail: msg });
  }
  warning2(msg?: string) {
    msg = msg != undefined ? msg : '请选择要操作的数据！';
    this.storage.makesureService.emit({
      message: msg,
      header: '提示',
      icon: '',
      rejectVisible: false,
      accept: () => { },
      reject: () => { }
    });
  }

}
